<template>
  <div class="bg course-container">

    <!-- 查询区域 -->
    <div>
      <el-input style="width: 200px" clearable prefix-icon="el-icon-c-scale-to-original"
                @keyup.enter.native="load(1)" placeholder="查询名称" v-model="name"></el-input>
      <el-input style="width: 200px; margin: 0 5px" clearable prefix-icon="el-icon-c-scale-to-original"
                @keyup.enter.native="load(1)" placeholder="查询地点" v-model="place"></el-input>
      <el-button type="primary" style="margin: 0 5px" @click="load(1)">查询</el-button>
      <el-button type="info" style="margin: 0 5px" @click="reset">重置</el-button>
      <el-select style="margin: 0 5px" v-model="type" placeholder="筛选课程类型">
        <el-option label="道路知识（科一）" value="道路知识（科一）"></el-option>
        <el-option label="场地驾驶（科二）" value="场地驾驶（科二）"></el-option>
        <el-option label="道路驾驶（科三）" value="道路驾驶（科三）"></el-option>
        <el-option label="安全考试（科四）" value="安全考试（科四）"></el-option>
        <el-option label="其他类型" value="其他类型"></el-option>
      </el-select>
      <el-select style="margin: 0 5px" v-model="state" placeholder="筛选课程状态">
        <el-option label="可预约" value="可预约"></el-option>
        <el-option label="待安排" value="待安排"></el-option>
        <el-option label="不可用" value="不可用"></el-option>
      </el-select>

    </div>

    <!-- 增删区域 -->
    <div style="margin: 10px 0; height: 35px">
      <el-button type="primary" plain @click="handleAdd">新增</el-button>
      <el-button type="danger" plain @click="delBatch">批量删除</el-button>
      <el-button type="info" plain v-if="user.role === '管理员'"
                 @click="exportData">批量导出</el-button>
      <el-upload action="http://localhost:9090/course/import"
                 v-if="user.role === '管理员'"
                 :on-success="handleImport"
                 :show-file-list="false"
                 style="display: inline-block; margin-left: 10px">
        <el-button type="info" plain>批量导入</el-button>
      </el-upload>
    </div>

    <!-- 数据表格区域 -->
    <el-table :data="tableData" stripe class="datatable"
              :header-cell-style="{ backgroundColor: 'aliceblue', color: '#666' }"
              @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"></el-table-column>
      <el-table-column prop="name" label="名称" sortable></el-table-column>
      <el-table-column prop="description" show-overflow-tooltip label="介绍"></el-table-column>
      <el-table-column prop="type" label="类型" sortable></el-table-column>
      <el-table-column prop="days" label="时长/天" sortable></el-table-column>
      <el-table-column prop="time" label="时间" sortable></el-table-column>
      <el-table-column prop="place" label="地点" sortable></el-table-column>
      <el-table-column prop="state" label="状态" sortable></el-table-column>
      <el-table-column label="操作" align="center" width="180">
        <template v-slot="scope">
          <el-button size="mini" type="primary" plain @click="handleEdit(scope.row)">编辑</el-button>
          <el-button size="mini" type="danger" plain @click="del(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页器区域 -->
    <div style="margin: 10px 0">
      <el-pagination
          @current-change="handleCurrentChange"
          :current-page="pageNum"
          :page-sizes="[100, 200, 300, 400]"
          :page-size="pageSize"
          layout="total, prev, pager, next"
          :total="total">
      </el-pagination>
    </div>

    <!-- 步骤条 -->
    <div style="position: relative; top: 15px;">
      <el-steps :active="1" align-center>
        <el-step title="发布课程信息" icon="el-icon-c-scale-to-original" description="请核实相关课程信息"></el-step>
        <el-step title="学员预约课程" icon="el-icon-c-scale-to-original" description="学员根据需求预约课程"></el-step>
        <el-step title="审核处理" icon="el-icon-circle-check" description="处理人负责指导该学员和教授课程"></el-step>
        <el-step title="完成预约" icon="el-icon-circle-check" description="在完成相关内容后即视为完成"></el-step>
        <el-step title=学员评价 icon="el-icon-document" description="学员可为相关教练和课程进行评价"></el-step>
      </el-steps>
    </div>

    <!-- 编辑/新增对话框 -->
    <el-dialog title="课程信息" :visible.sync="fromVisible" width="30%">
      <el-form :model="form" label-width="80px" style="padding-right: 20px" :rules="rules" ref="formRef">
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" @keyup.enter.native="save()"
                    placeholder="请输入课程名称"></el-input>
        </el-form-item>
        <el-form-item label="介绍" prop="description">
          <el-input type="textarea" v-model="form.description" @keyup.enter.native="save()"
                    placeholder="请输入详细课程介绍或者描述"></el-input>
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <el-radio-group v-model="form.type" style="display: block;">
            <el-radio label="道路知识（科一）"></el-radio>
            <el-radio label="场地驾驶（科二）"></el-radio>
            <el-radio label="道路驾驶（科三）"></el-radio>
            <el-radio label="安全考试（科四）"></el-radio>
            <el-radio label="其他类型"></el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="时长/天" prop="days">
          <el-input v-model="form.days" @keyup.enter.native="save()"
                    placeholder="请输入持续时长"></el-input>
        </el-form-item>
        <el-form-item label="时间" prop="time">
          <el-input v-model="form.time" @keyup.enter.native="save()"
                    placeholder="请输入开始时间及结束时间"></el-input>
        </el-form-item>
        <el-form-item label="地点" prop="place">
          <el-input v-model="form.place" @keyup.enter.native="save()"
                    placeholder="请输入课程地点"></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="state">
          <el-radio-group v-model="form.state">
            <el-radio label="可预约"></el-radio>
            <el-radio label="待安排"></el-radio>
            <el-radio label="不可用"></el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="fromVisible = false">取 消</el-button>
        <el-button type="primary" @click="save">确 定</el-button>
      </div>
    </el-dialog>

  </div>
</template>


<script>
export default {
  name: "Course_info",

  // 组件的数据对象
  data() {
    return {
      user: JSON.parse(localStorage.getItem('honey-user') || '{}'), // 从本地存储获取用户信息
      tableData: [],  // 存储所有的课程信息数据
      pageNum: 1,   // 当前页码
      pageSize: 5,  // 每页显示的数据条数
      name: '', // 查询的课程名称
      place: '', // 查询的课程地点
      type: '', // 查询的课程类型
      state: '', // 查询的课程状态
      total: 0, // 数据的总数
      fromVisible: false, // 控制新增/编辑对话框的显示与隐藏
      form: {}, // 存储表单数据
      rules: {
        name: [
          { required: true, message: '请输入课程名称', trigger: 'blur' },
        ]
      },
      ids: [] // 存储选中的课程 ID 数组
    }
  },

  // 组件创建时调用 load 方法加载数据
  created() {
    this.load()
  },

  methods: {
    // 批量删除方法
    delBatch() {
      // 判断是否有选中的数据
      if (!this.ids.length) {
        this.$message.warning('请选择数据')
        return
      }
      // 弹出确认删除的提示框
      this.$confirm('您确认批量删除这些数据吗？', '确认删除', {type: "warning"}).then(response => {
        // 发送删除请求
        this.$request.delete('/course/delete/batch', { data: this.ids }).then(res => {
          if (res.code === '200') {   // 操作成功
            this.$message.success('操作成功')
            this.load(1)
          } else {
            this.$message.error(res.msg)  // 弹出错误的信息
          }
        })
      }).catch(() => {})
    },

    // 处理表格行选中变化
    handleSelectionChange(rows) {   // 获取选中的行数据
      this.ids = rows.map(v => v.id)
    },

    // 删除单条数据方法
    del(id) {
      // 弹出确认删除的提示框
      this.$confirm('您确认删除吗？', '确认删除', {type: "warning"}).then(response => {
        // 发送删除请求
        this.$request.delete('/course/delete/' + id).then(res => {
          if (res.code === '200') {   // 操作成功
            this.$message.success('操作成功')
            this.load(1)
          } else {
            this.$message.error(res.msg)  // 弹出错误的信息
          }
        })
      }).catch(() => {})
    },

    // 批量导出 excel
    exportData() {
      // 判断是否有选中的数据，决定导出的范围
      if (!this.ids.length) {
        window.open('http://localhost:9090/course/export?name=' + this.name)
      } else {
        let idStr = this.ids.join(',')
        window.open('http://localhost:9090/course/export?ids=' + idStr);
      }
    },

    // 批量导入 excel
    handleImport(res, file, fileList) {
      if (res.code === '200') {
        this.$message.success("操作成功")
        this.load(1)
      } else {
        this.$message.error(res.msg)
      }
    },

    // 编辑数据方法
    handleEdit(row) {   // 编辑数据
      this.form = JSON.parse(JSON.stringify(row))  // 深拷贝数据
      this.fromVisible = true   // 打开弹窗
    },

    // 新增数据方法
    handleAdd() {   // 新增数据
      this.form = {type:'其他类型', state: '待安排', time:'00:00-00:00'}
      this.fromVisible = true   // 打开弹窗
    },

    // 保存数据方法
    save() {   // 保存按钮触发的逻辑
      // 表单验证
      this.$refs.formRef.validate((valid) => {
        if (valid) {
          // 根据是否有 ID 判断是新增还是更新
          this.$request({
            url: this.form.id ? '/course/update': '/course/add',
            method: this.form.id ? 'PUT' : 'POST',
            data: this.form
          }).then(res => {
            if (res.code === '200') {  // 保存成功
              this.$message.success('保存成功')
              this.load(1)
              this.fromVisible = false
            } else {
              this.$message.error(res.msg)  // 弹出错误的信息
            }
          })
        }
      })
    },

    // 重置查询条件方法
    reset() {
      this.name = ''
      this.place=''
      this.type= ''
      this.load()
    },

    // 加载数据方法
    load(pageNum) {  // 分页查询
      if (pageNum)  this.pageNum = pageNum
      // 发送请求获取分页数据
      this.$request.get('/course/selectByPage', {
        params: {
          pageNum: this.pageNum,
          pageSize: this.pageSize,
          name: this.name,
          place: this.place,
          type: this.type,
          state: this.state,
          description:'',
          time: '',
        }
      }).then(res => {
        this.tableData = res.data.records
        this.total = res.data.total
      })
    },

    // 处理分页变化方法
    handleCurrentChange(pageNum) {
      this.load(pageNum)
    },

  }
}
</script>


<style scoped>
.course-container {
  background: url('@/assets/bg/course.png') center/cover no-repeat;
}
</style>